<?php
/**
* $Id: admin.php 2942 2009-11-30 10:48:18Z huong.pham $
*/
require_once('backend.php');
class Admin extends Backend
{  
    function Admin()
    {
        parent::Backend();
        $this->load->model('MUser');
        
        $this->load->library('User');
        $this->load->library('session');
    }
    
    public function accessRules(){
        return array(
            'login' => '',
            'logout' => '',
            'lostPassword' => '', 
            '*' => 'admin'
        );
    }
    
    public function index()
    {
        //CSS
        $this->layout[AppContants::LAYOUT_CSS] =  array('common', 'tablesorter', 'tabs');
        //JS
        $this->layout[AppContants::LAYOUT_JS] = array('jquery.tabs', 'jquery.tablesorter', 'shadowbox-2.0/adapter/shadowbox-jquery', 'shadowbox-2.0/shadowbox',);
        //Main layout
        $this->layout[AppContants::LAYOUT_MAINVIEW] = "admin/list";   
    }
    
    /**
    * Login
    * 
    */
    public function login(){
        //If user has logged in, send him out of this page
        
        if (!$this->user->isGuest() && array_search('admin',$this->user->roles) !== false)
        {
            redirect('admin');            
        }
        //Validation
        $this->load->model('MUser'); 
        $this->load->library('form_validation');
        //Set validate delimiter error
        $this->form_validation->set_error_delimiters('<em class="Error" id="serverError">', '</em>');        

        $fields = $this->MUser->fields();
        //$this->form_validation->set_fields($fields);

        //Set validation rules 
        $this->form_validation->set_rules($this->MUser->getRules('login'));
        //Check validation
        if ($this->form_validation->run() === FALSE)
        {
            //CSS
            $this->layout[AppContants::LAYOUT_CSS] = array('login');
            //Js
            $this->layout[AppContants::LAYOUT_JS] = array("jquery.validate");
            //No navigation and footer.
            $this->layout[AppContants::LAYOUT_TOP] = "";
            $this->layout[AppContants::LAYOUT_BOTTOM] = "";
            //Main view
            $this->layout[AppContants::LAYOUT_MAINVIEW] = "admin/login" ; 
                   
        }
        else
        {  
            $url = $this->user->getRedirectUrl();
            if (empty($url) || $url == 'admin/login')
            {
                $url = 'admin'; 
            }
            redirect($url);
        }   
    }
    
    /**
    * custome rule applied on email field when login
    *     
    * @param mixed $email
    */
    public function loginCheck ($value)
    {
        $email = $this->validation->email;  
        if (($err = $this->tryLogin($email, $value)) != UserIdentity::ERR_NONE)
            return TRUE;
        else{
            return FALSE; 
        }            
    } 
    
    public function emailCheck ($email)
    {
        $accountInfo = $this->MUser->selectDetails()->getByEmailAndPassword($email);   
        if(!empty($accountInfo))
        {
            return TRUE;   
        }
        $this->validation->set_message('emailCheck', $this->config->item('no_email_exist'));
        return FALSE;
    }
    
    /**
     * Attempt to login using the given condition
     *
     * Accepts an associative array as input, containing login condition
     * Example: $this->login(array('email'=>$email, 'password'=>dohash($password)))
     *
     * @access    protected
     * @param    array    login conditions
     * @return    boolean
     */    
    protected function tryLogin($username, $password) 
    {
        //Advoid harm code attack
        $username = safeParam($username);
        $password = safeParam($password);
        
        $ui = $this->user->createIdentity($username, $password);
        $ret = $ui->authorize();
        switch ($ret){
            case UserIdentity::ERR_INVALID_IDENTITY:
                $err = $this->config->item('incorrect_login');
                break;
            case UserIdentity::ERR_INACTIVE_IDENTITY:
                $err = $this->config->item('account_not_active');
                $err = str_replace('%s', site_url('member/resend_activate'), $err); 
                break;
            case UserIdentity::ERR_NONE:
                $this->user->login($ui);
                if (!empty($this->user->Id) && $this->user->Id != $this->config->item('admin_id'))
                {
                    $err = $this->config->item('member_access_bo');    
                }
                else
                {
                    return true;
                }
                break;
        }                              
        $this->validation->set_message('loginCheck', $err);                         
        return false;
    }
    
    /**
    * Logout
    * 
    */
    public function logout(){
        $this->user->logout();
        redirect('');    
    }
    
    /**
    * Lost Password
    * 
    */
    public function lostPassword()
    {
        //Set rule validation.
        $this->load->library('validation');
        $this->validation->set_rules($this->MUser->getRules('lost_password'));
        
        //Set validate delimiter error
        $this->validation->set_error_delimiters('<em class="Error" id="serverError">', '</em>');
        
        if ($this->validation->run() == FALSE) 
        {   
            //CSS
            $this->layout[AppContants::LAYOUT_CSS] = array('login');
            //Js
            $this->layout[AppContants::LAYOUT_JS] = array("jquery.validate");
            //No navigation and footer.
            $this->layout[AppContants::LAYOUT_TOP] = "";
            $this->layout[AppContants::LAYOUT_BOTTOM] = "";
            //Main View
            $this->layout[AppContants::LAYOUT_MAINVIEW] = 'admin/login';     
        }
        else
        { 
            //Get accountInfo
            $accountInfo = $this->MUser->selectDetails()->getByEmailAndPassword($this->validation->userEmail); 
            $newPassword = $this->random_gen(6);  
            //Update userInfo
            $this->MUser->update(array('password'=>md5($newPassword)), array('id'=>$accountInfo['id']));
            
            //Send mail
            //Load library send mail
            $this->load->library('qs_mailer');
            $this->load->config('qs_email'); 
            $to[0] = $this->validation->userEmail;
            $to[1] = $accountInfo['first_name']." ".$accountInfo['last_name'];
            $from[0] = $this->config->item('admin_email');
            $from[1] = $this->config->item('admin_name');
            
            //Configuration smtp
            $config = array();
            $config['SendMailMethod'] = $this->config->item('SendMailMethod');
            $config['SMTPHost'] = $this->config->item('SMTPHost');
            $config['SMTPPort'] = $this->config->item('SMTPPort');
            $config['SMTPSecure'] = $this->config->item('SMTPSecure');
            $config['SMTPSender'] = $this->config->item('SMTPSender');
            $config['SMTPPassword'] = $this->config->item('SMTPPassword');
            
            $mailInfo = new stdClass(); 
            $mailInfo->urlHome = base_url();
            $mailInfo->username = $accountInfo['email'];
            $mailInfo->password = $newPassword;
            $info = array (
                'subject' =>$this->config->item('new_password_subject').$accountInfo['first_name']." ".$accountInfo['last_name'],
                'template' => 'new_password.html',
                'to' => $to,
                'from' => $from,
                'mailInfo' => $mailInfo,
                'config' => $config,
            ); 
            //Send mail
            QS_Mailer::sendMail($info);
            $msg = $this->config->item('password_sent'); 
            $this->showMessage($msg, 'admin', false);
        }           
    }
    
    /**
    * Random gen activation key
    * 
    * @param mixed $length
    */
    protected function random_gen($length)
    {
        $random= "";
        srand((double)microtime()*1000000);
        $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $char_list .= "abcdefghijklmnopqrstuvwxyz";
        $char_list .= "1234567890";
        // Add the special characters to $char_list if needed

        for($i = 0; $i < $length; $i++)
        {
        $random .= substr($char_list,(rand()%(strlen($char_list))), 1);
        }
        return $random;
    }
}  
?>
